package mytaxis.client.app;

//BORRA AIXO
import mytaxis.client.R;
import mytaxis.client.login.Index;
import mytaxis.client.login.Register;
import mytaxis.client.menu.Titular;
import mytaxis.client.service.ComService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BookList extends Activity{
	
	MyTaxisClientApplication app;
	ProgressDialog pd;
	private ComService mBoundService;	

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
		    mBoundService = ((ComService.LocalBinder)service).getService();
		}
	
		public void onServiceDisconnected(ComponentName className) {
		    mBoundService = null;
		}
		};
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bookingprop);		
		app = (MyTaxisClientApplication) getApplication();
		startService(new Intent(BookList.this, ComService.class));
		bindService(new Intent(this, ComService.class), mConnection, Context.BIND_AUTO_CREATE);
		
		app.setBook(true);
		initViews();
		
	}
	
	protected void onDestroy() {
		super.onDestroy();
		app.setBook(false);
	}
	
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			boolean result = msg.getData().getBoolean("result");
			if(result){
				initViews();
				Toast.makeText(getApplicationContext(),"Request cancelled", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(),"Error cancelling the request", Toast.LENGTH_SHORT).show();
			}
		};
	};
	
	private void initViews(){
		
		int mida_string =0; //mida string
		int j = 0;
		if(app.getNumPeticio() >= 0) mida_string++; //si hi ha peticions immediates
		
		if(app.getlistPeticions() != null) {
			Titular res[] = app.getlistPeticions();
			mida_string += res.length;
		}
		
		Titular r[] = new Titular[mida_string];
		if(app.getNumPeticio() >= 0){
	        	String ass = app.getNomTaxista();
	        	if(ass == null) ass = "No taxist accepted the request for the moment";
	        	r[j]= new Titular("Immediate Request Id: "+ app.getNumPeticio(), ass);
	        	j++;
	        }
		if(app.getlistPeticions() != null){
			Titular res[] = app.getlistPeticions();
			for (int c=0; c < res.length; c++){
				r[j] = res[c];
				j++;
			}
		}
		if(r!= null){
			try{
			
			AdaptadorTitulares adaptador =
			        new AdaptadorTitulares(this,r);
			
			ListView lstOpciones = (ListView)findViewById(R.id.LstOpciones);
			 
			lstOpciones.setAdapter(adaptador);
		
			}
			catch(Exception e){
				Log.d("exc",e.toString());
			}
		}
	}
	
	class AdaptadorTitulares extends ArrayAdapter<Object> {
		 
	    Activity context;
	    Titular[] datos;
	 
			AdaptadorTitulares(Activity context, Titular[] datos) {
	            super(context, R.layout.listitem_titular, datos);
	            this.context = context;
	            this.datos = datos;
	        }
	 
	        public View getView(int position, View convertView, ViewGroup parent) {
	        LayoutInflater inflater = context.getLayoutInflater();
	        View item = inflater.inflate(R.layout.listitem_titular, null);
	 
	        final TextView lblTitulo = (TextView)item.findViewById(R.id.LblTitulo);
	        lblTitulo.setText(datos[position].getTitulo());
	 
	        TextView lblSubtitulo = (TextView)item.findViewById(R.id.LblSubTitulo);
	        lblSubtitulo.setText(datos[position].getSubtitulo());
	        
	        item.setOnClickListener(new OnClickListener() {
	        	public void onClick(View v) {
		        	new AlertDialog.Builder(context)
			        	.setTitle("Cancel Request")
			        	.setMessage("Are you sure you want to cancel the request?")
			        	.setPositiveButton("Yes",
			        	new DialogInterface.OnClickListener() {
			        	public void onClick(DialogInterface dialog,
			        	int whichButton) {;
				        	String s[] = lblTitulo.getText().toString().split(": ");
				        	final int id = Integer.parseInt(s[1]);
				        	
				        	Thread t = new Thread(){
					        	public void run(){
					        	
					        	boolean res = mBoundService.cancel_peticio(id);
					        	
					        	Message msg = new Message();
					        	Bundle b = new Bundle();
					        	b.putBoolean("result", res);
					        	msg.setData(b);
					        	mHandler.sendMessage(msg);
					        	};
					        	};
					        t.start();
			        	}
			        	})
		        	.setNegativeButton("No",
		        	new DialogInterface.OnClickListener() {
		        	public void onClick(DialogInterface dialog,
		        	int whichButton) {
		        	// ignore, just dismiss
		        	}
		        	}).show();
	
		        	}
	

	        	});
	        
	     
	 
	        return(item);
	    }
	}
}
